﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using WMM.Tapioca.Instance;
using WMM.Tapioca.Taxonomy;
using WMM.Tapioca.Linkbase;
using System.Xml.Linq;
using WMM.Tapioca.Utilities;

namespace WMM.Tapioca.Formula.Filters
{
    /// <summary>
    /// The non-XDT segment matching filter can be used to select facts that have the same segment,
    /// after excluding any XBRL Dimensions Specification content from the comparison. 
    /// </summary>
    public class MatchNonXDTSegmentFilter : MatchFilter
    {
        /// <summary>
        /// Constructor.
        /// </summary>
        public MatchNonXDTSegmentFilter(Resource resource)
            : base(resource)
        {
            
        }


        public override List<FactItem> EvaluateFilter(VariableSet variableSet, List<FactItem> itemsToFilter, DTS dts)
        {
            this.dts = dts;
            namespaces = dts.DtsFormula.Namespaces;

            List<FactItem> itemListTemp = new List<FactItem>();

            foreach (FactItem itemToFilter in itemsToFilter)
            {
                List<FactItem> factItems = variableSet.variableItems[Variable];

                XElement context = new XElement(itemToFilter.ContextRef.ContextElement);

                context.Descendants(Constants.XBRLDI + "explicitMember").Remove();
                context.Descendants(Constants.XBRLDI + "typedMember").Remove();
                XElement segment = context.Descendants(Constants.XBRLI + "segment").FirstOrDefault();

                for (int i = 0; i < factItems.Count; i++)
                {
                    XElement contextToCompare = new XElement(factItems[i].ContextRef.ContextElement);

                    contextToCompare.Descendants(Constants.XBRLDI + "explicitMember").Remove();
                    contextToCompare.Descendants(Constants.XBRLDI + "typedMember").Remove();
                    XElement segmentToCompare = contextToCompare.Descendants(Constants.XBRLI + "segment").FirstOrDefault();

                    if (Complement ? !XNode.DeepEquals(segment, segmentToCompare) : XNode.DeepEquals(segment, segmentToCompare))
                    {
                        itemListTemp.Add(itemToFilter);
                        continue;
                    }
                }
            }

            return itemListTemp;
        }
    }
}
